package com.linc.intercept;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

/**
 * Created by linc on 15-7-12.
 */
public class SmsReceiver extends BroadcastReceiver {
    private static final String TAG = "SmsReceiver";
    public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.d(TAG,"action: "+action);
        if (SMS_RECEIVED_ACTION.equals(action)) {
            Bundle bundle = intent.getExtras();
            StringBuffer messageContent = new StringBuffer();
            if (bundle != null) {
                Object[] pdus = (Object[]) bundle.get("pdus");
                for (Object pdu : pdus) {
                    SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
                    String sender = message.getOriginatingAddress();
                    Log.d(TAG,"sender: "+sender);
                    if ("10086".equals(sender) || "10010".equals(sender) ||
                            "10001".equals(sender)) {
                        messageContent.append(message.getMessageBody());
                    }
                }
                if(!messageContent.toString().isEmpty()) {
                    Log.d(TAG,"send message broadcast.");
                    Intent intentBroadcast = new Intent();
                    intentBroadcast.putExtra("message", messageContent.toString());
                    intentBroadcast.setAction("sms_received");
                    context.sendBroadcast(intentBroadcast);
                    Log.d(TAG, "send broadcast and abort");
//                    abortBroadcast();
                }
            }
        }
    }
}
